﻿using ASmile.Helpers;
using ASmile.ORM.Cores;
using ASmile.ORM.Entitys;

namespace ASmile.Com.Da
{
    /// <summary>
    /// 分页查询基类
    /// </summary>
    /// <typeparam name="TPageArg">查询参数类型</typeparam>
    /// <typeparam name="TListModel">查询结果类型</typeparam>
    public abstract class BLLReadPager<TPageArg, TListModel> : BLLBase
        where TPageArg : ArgPageData, new()
        where TListModel : class, new()
    {
        protected abstract void SetQuery(QueryCondition<TListModel> query, TPageArg arg);

        public virtual ApiResultList<TListModel> GetList(TPageArg arg)
        {
            var rList =
            GetPagerList<TListModel>(arg, out int total, query =>
            {
                SetQuery(query, arg);
            });
            return this.RetOK(rList, total);
        }
    }

    /// <summary>
    /// 增删查改基类 1
    /// </summary>
    /// <typeparam name="TPageArg">查询参数</typeparam>
    /// <typeparam name="TSaveModel">保存实体类型</typeparam>
    /// <typeparam name="TListModel">查询结果类型</typeparam>
    public abstract class BLLCrudBase<TPageArg, TSaveModel, TListModel> : BLLReadPager<TPageArg, TListModel>, IBLLCrud<TPageArg, TSaveModel, TListModel> 
        where TPageArg : ArgPageData, new()
        where TSaveModel : EntityBase, new()
        where TListModel : class, new()
    {
        protected abstract ApiResult<string> VerifyModel(TSaveModel model, bool isAdd);

        public virtual ApiResult<string> Add(TSaveModel model)
        {
            var ret = VerifyModel(model, true);
            if (ret)
            {
                DB.Insert(model);
            }
            return ret;
        }

        public virtual ApiResult<string> Update(TSaveModel model)
        {
            var ret = VerifyModel(model, false);
            if (ret)
            {
                DB.Update(model);
            }
            return ret;
        }

        public virtual ApiResult Del(TSaveModel model)
        {
            var ret = DB.Delete(model);
            if (ret.RowCount == 1)
            {
                return RetOK("删除成功");
            }
            return RetErr("删除失败");
        }
    }

    /// <summary>
    /// 增删查改基类 重载
    /// </summary>
    public abstract class BLLCrudBase<TPageArg, TSaveModel> : BLLCrudBase<TPageArg, TSaveModel, TSaveModel>, IBLLCrud<TPageArg, TSaveModel>
        where TPageArg : ArgPageData, new()
        where TSaveModel : EntityBase, new()
    { }

    public abstract class BLLCrudBase<TSaveModel> : BLLCrudBase<ArgPageData, TSaveModel, TSaveModel>, IBLLCrud<TSaveModel>
        where TSaveModel : EntityBase, new()
    { }
}